using MediatR;
using MeetingManagement.Application.Common;
using MeetingManagement.Domain.Entities;
using MeetingManagement.Domain.Repositories;

namespace MeetingManagement.Application.Commands.Users.UpdateUser
{
    public class UpdateUserCommandHandler : IRequestHandler<UpdateUserCommand, UpdateUserResult>
    {
        private readonly IRepository<User> _userRepository;
        private readonly IPasswordHasher _passwordHasher;

        public UpdateUserCommandHandler(IRepository<User> userRepository, IPasswordHasher passwordHasher)
        {
            _userRepository = userRepository;
            _passwordHasher = passwordHasher;
        }

        public async Task<UpdateUserResult> Handle(UpdateUserCommand request, CancellationToken cancellationToken)
        {
            var user = await _userRepository.GetAsync(request.Id);
            if (user == null)
            {
                return new UpdateUserResult
                {
                    Success = false,
                    Message = "User not found"
                };
            }

            // Check if username is taken by another user
            if (_userRepository.Query().Any(u => u.Username == request.Username && u.Id != request.Id))
            {
                return new UpdateUserResult
                {
                    Success = false,
                    Message = "Username already exists"
                };
            }

            // Check if email is taken by another user
            if (_userRepository.Query().Any(u => u.Email == request.Email && u.Id != request.Id))
            {
                return new UpdateUserResult
                {
                    Success = false,
                    Message = "Email already exists"
                };
            }

            // Update user information
            user.UpdateInfo(request.Username, request.Email);

            // Update password if requested
            if (request.UpdatePassword && !string.IsNullOrEmpty(request.Password))
            {
                string passwordHash = _passwordHasher.Hash(request.Password);
                user.UpdatePassword(passwordHash);
            }

            await _userRepository.UpdateAsync(user);

            return new UpdateUserResult
            {
                Success = true,
                Message = "User updated successfully",
                User = user
            };
        }
    }
}
